from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QDialog, QLineEdit, QGridLayout, QMenu
from PySide6.QtGui import QCursor
from .widgets.panels import BasePanel
from .widgets.table_widget import CommonTableWidget
from .widgets.dialogs import BaseDialog, MessageOverlay
from .widgets.basewidgets import *
from api import api
from common import config, utils, exceptions

USER_HEADER_COLUMNS = {
    "用户名": {"type": "text", "text": lambda x: x["username"]},
    "角色": {"type": "text", "text": lambda x: utils.UserRole(x["role"]).description},
    "状态": {"type": "text", "text": lambda x: "启用" if x["status"] else "禁用", "color": lambda x: "" if x["status"] else "red"},
    "创建时间": {"type": "text", "text": lambda x: utils.format_datetime(x["created_at"])},
    "最后登录时间": {"type": "text", "text": lambda x: utils.format_datetime(x["last_login_at"]) if x.get("last_login_at") else "--"},
    "操作": {"type": "action"}
}

class UserPage(BasePanel):
    def __init__(self):
        super().__init__("用户管理")
        self.setup_ui()
        self.setup_context_menu()
    
    def setup_ui(self):
        # 搜索和操作区域
        search_widget = SearchPanel()
        search_layout = QHBoxLayout(search_widget)
        
        # 搜索区域
        self.search_input = SearchLineEdit()
        self.search_input.setPlaceholderText("根据用户名搜索")
        self.search_input.textChanged.connect(self.flush_table)
        
        # 角色筛选
        self.role_combo = NormalComboBox()
        role_items = {"全部角色": ""}
        for role in utils.UserRole:
            role_items[role.description] = role.value
        self.role_combo.setItems(role_items)
        self.role_combo.currentIndexChanged.connect(self.flush_table)
        
        # 状态筛选
        self.status_combo = NormalComboBox()
        self.status_combo.setItems({
            "全部状态": None,
            "启用": True,
            "禁用": False
        })
        self.status_combo.currentIndexChanged.connect(self.flush_table)
        
        # 添加用户按钮
        self.add_btn = BluePushButton("添加用户")
        self.add_btn.clicked.connect(self.show_add_user_dialog)
        
        # 将所有控件添加到顶部布局
        search_layout.addWidget(self.search_input)
        search_layout.addWidget(self.role_combo)
        search_layout.addWidget(self.status_combo)
        search_layout.addStretch()
        search_layout.addWidget(self.add_btn)
        
        self.main_layout.addWidget(search_widget)
        
        # 用户表格
        table_widget = QWidget()
        table_widget.setObjectName("userTable")
        table_layout = QVBoxLayout(table_widget)
        
        self.user_table = CommonTableWidget(headers=USER_HEADER_COLUMNS)
        
        table_layout.addWidget(self.user_table)
        self.main_layout.addWidget(table_widget)

    def setup_context_menu(self):
        super().setup_context_menu()
        self.user_table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.user_table.customContextMenuRequested.connect(self.show_context_menu)

    def add_extra_context_menus(self, menu, pos):
        menu.addSeparator()
        add_user_action = menu.addAction("添加用户")
        add_user_action.triggered.connect(self.show_add_user_dialog)
        
        # 如果是在表格中点击
        sender = self.sender()
        if sender == self.user_table and self.user_table.itemAt(pos):
            row = self.user_table.itemAt(pos).row()
            user_data = self.user_table.get_row_data(row)
            
            menu.addSeparator()
            
            # 用户操作子菜单
            operations_menu = menu.addMenu("用户操作")
            operations_menu.addAction("编辑").triggered.connect(
                lambda: self.edit_user(row))
                
            if user_data["status"]:
                status_action = operations_menu.addAction("禁用")
                status_action.triggered.connect(lambda: self.toggle_user_status(row, False))
            else:
                status_action = operations_menu.addAction("启用")
                status_action.triggered.connect(lambda: self.toggle_user_status(row, True))
                
            delete_action = operations_menu.addAction("删除")
            delete_action.triggered.connect(lambda: self.delete_user(row))
            
            menu.addSeparator()
            
            # 用户信息子菜单
            info_menu = menu.addMenu("用户信息")
            info_menu.addAction(f"用户名: {user_data['username']}")
            info_menu.addAction(f"角色: {utils.UserRole(user_data['role']).description}")
            info_menu.addAction(f"状态: {'启用' if user_data['status'] else '禁用'}")
            info_menu.addAction(f"创建时间: {utils.format_datetime(user_data['created_at'])}")
            if user_data.get('last_login_at'):
                info_menu.addAction(f"最后登录: {utils.format_datetime(user_data['last_login_at'])}")
    
    def load_data(self):
        """初始加载数据"""
        self.flush_table()
    
    def flush_table(self):
        """刷新表格数据"""
        users = api.get_users(
            username=self.search_input.text(),
            role=self.role_combo.currentData(),
            status=self.status_combo.currentData(),
            page=self.user_table.current_page,
            per_page=self.user_table.page_size
        )
        if not users:
            return
            
        self.user_table.set_total_items(users["count"])
        self.user_table.setRowCount(len(users["items"]))
        for i, user in enumerate(users["items"]):
            self.user_table.set_row_data(i, user)
            action_buttons = []
            
            # 根据用户状态添加不同的按钮
            if user["status"]:
                action_buttons.append({
                    "text": "禁用",
                    "callback": lambda x:self.toggle_user_status(x, status=False),
                    "objectName": "deleteButton"
                })
            else:
                action_buttons.append({
                    "text": "启用",
                    "callback": lambda x:self.toggle_user_status(x, status=True)
                })
            
            # 添加编辑和删除按钮
            action_buttons.extend([
                {"text": "编辑", "callback": self.edit_user},
                {"text": "删除", "callback": self.delete_user, "objectName": "deleteButton"}
            ])
            
            self.user_table.add_action_buttons(i, action_buttons)
    
    def show_add_user_dialog(self):
        """显示添加用户对话框"""
        dialog = UserFormDialog(self)
        if dialog.exec() == QDialog.Accepted:
            api.add_user(**dialog.get_data())
            MessageOverlay.info(self, "用户添加成功")
            self.flush_table()
    
    def edit_user(self, row):
        """编辑用户"""
        user_data = self.user_table.get_row_data(row)
        dialog = UserFormDialog(self, user_data)
        if dialog.exec() == QDialog.Accepted:
            api.update_user(user_data["id"], **dialog.get_data())
            MessageOverlay.info(self, "用户信息更新成功")
            self.flush_table()
    
    def toggle_user_status(self, row, status):
        """切换用户状态"""
        user_data = self.user_table.get_row_data(row)
        action = "启用" if status else "禁用"
        if MessageOverlay.question(self, f"确定要{action}用户 {user_data['username']} 吗？") == MessageOverlay.ACCEPTED:
            api.update_user(user_data["id"], status=status)
            MessageOverlay.info(self, f"用户已{action}")
            self.flush_table()
    
    def delete_user(self, row):
        """删除用户"""
        user_data = self.user_table.get_row_data(row)
        if MessageOverlay.question(self, f"确定要删除用户 {user_data['username']} 吗？此操作不可恢复！") == MessageOverlay.ACCEPTED:
            api.delete_user(user_data["id"])
            MessageOverlay.info(self, "用户删除成功")
            self.flush_table()

class UserFormDialog(BaseDialog):
    def __init__(self, parent=None, user_data=None):
        super().__init__(parent)
        self.user_data = user_data
        self.setup_ui()
        
    def setup_ui(self):
        self.setWindowTitle("编辑用户" if self.user_data else "添加用户")
        self.setMinimumWidth(400)
        
        layout = QVBoxLayout(self)
        
        # 表单布局
        form_layout = QGridLayout()
        
        # 用户名
        self.username_input = NormalLineEdit()
        if self.user_data:
            self.username_input.setReadOnly(True)
        form_layout.addWidget(NormalLabel("用户名:"), 0, 0)
        form_layout.addWidget(self.username_input, 0, 1)
        
        # 密码
        self.password_input = NormalLineEdit()
        self.password_input.setEchoMode(QLineEdit.Password)
        if self.user_data:
            self.password_input.setPlaceholderText("不修改请留空")
        form_layout.addWidget(NormalLabel("密码:"), 1, 0)
        form_layout.addWidget(self.password_input, 1, 1)
        
        # 角色
        self.role_combo = NormalComboBox()
        self.role_combo.setItems({role.description: role.value for role in utils.UserRole})
        if not self.user_data:
            self.role_combo.setCurrentIndex(self.role_combo.count() - 1)
        form_layout.addWidget(NormalLabel("角色:"), 2, 0)
        form_layout.addWidget(self.role_combo, 2, 1)
        
        # 状态
        self.status_combo = NormalComboBox()
        self.status_combo.setItems({
            "启用": True,
            "禁用": False
        })
        form_layout.addWidget(NormalLabel("状态:"), 3, 0)
        form_layout.addWidget(self.status_combo, 3, 1)
        
        layout.addLayout(form_layout)
        
        # 如果是编辑模式，填充现有数据
        if self.user_data:
            self.username_input.setText(self.user_data["username"])
            self.role_combo.setCurrentText(utils.UserRole(self.user_data["role"]).description)
            self.status_combo.setCurrentText("启用" if self.user_data["status"] else "禁用")
        
        # 按钮布局
        button_layout = self.create_button_layout(self.validate_and_accept)
        layout.addLayout(button_layout)
    
    def validate_and_accept(self):
        """验证表单数据"""
        if not self.username_input.text():
            MessageOverlay.warning(self, "请输入用户名")
            return
        
        password = self.password_input.text()
        if not self.user_data and not password:
            MessageOverlay.warning(self, "请输入密码")
            return
        
        if len(password) < config.USER_PASSWORD_MIN_LENGTH:
            MessageOverlay.warning(self, f"密码长度至少为{config.USER_PASSWORD_MIN_LENGTH}个字符")
            return
        
        self.accept()
    
    def get_data(self):
        """获取表单数据"""
        data = {
            #"username": self.username_input.text(),
            "role": self.role_combo.currentData(),
            "status": self.status_combo.currentData(),
            "password": self.password_input.text()
        }
            
        return data